package com.firefly.admin.common.utils;



import com.firefly.admin.common.constant.Constants;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HttpClientUtil {
    public static String doPost(String reqUrl, Map<String, String> headerMap, Map<String, String> paramMap) {
        HttpURLConnection connection = null;
        BufferedReader br = null;
        PrintWriter pw = null;
        StringBuilder sb = new StringBuilder();
        try {
            URL url = new URL(reqUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(2000);
            connection.setReadTimeout(2000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod(Constants.Http.HTTP_METHOD_POST);
            connection.setUseCaches(false);
            if (headerMap != null && headerMap.size() > 0) {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    String key = entry.getKey();
                    String value = entry.getValue();
                    connection.setRequestProperty(key, value);
                }
            }
            pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()));
            StringBuilder parameter = new StringBuilder();
            parameter.append("1=1");
            if (paramMap != null && paramMap.size() > 0) {
                for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                    parameter.append("&").append(entry.getKey()).append("=").append(entry.getValue());
                }
            }
            pw.write(parameter.toString());
            pw.flush();
            pw.close();
            br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            String line = null;
            sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert pw != null;
                pw.close();
                assert br != null;
                br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return sb.toString();
    }
}
